<?php
/**
 * Created by PhpStorm.
 * 微信支付相关接口
 * User: 王金鑫
 * Date: 2018/8/23
 * Time: 18:13
 */
namespace app\facescore\home;
use app\common\controller\Common;
use think\Db;
use app\common\model\AdminAnnex as AnnexModel;
use think\Loader;
Loader::import('WxPay.WxPayPubHelper',EXTEND_PATH,'.php');

class Wxpay extends Common
{
    /**
     * 下单接口
     * @return \think\response\Json
     */
    public function wxpay(){

        $jsApi = new \JsApi_pub();
        $money =  (float)input("money", '', 'htmlspecialchars_decode') * 100;
        //$money = 1;
        $order_id = input("order_id");
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        $openid = input("openid", '', 'htmlspecialchars_decode');
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();

        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid",$openid);//商品描述
        $unifiedOrder->setParameter("body","购买vip");//商品描述
        $unifiedOrder->setParameter("sign_type","MD5");//商品描述
        $unifiedOrder->setParameter("device_info","WEB");//商品描述
        //自定义订单号，此处仅作举例
        $timeStamp = time();

        $out_trade_no = 'FACESCORE'.$order_id;
        $unifiedOrder->setParameter("out_trade_no", "$out_trade_no");//商户订单号
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url",\WxPayConf_pub::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

        $arr = array();
        $arr['prepay_id'] = $unifiedOrder->getPrepayId();
        $arr['nonce_str']=$unifiedOrder->parameters["nonce_str"];
        $arr['timeStamp'] = (String)$timeStamp;

        $stringA="appId=".\WxPayConf_pub::APPID."&nonceStr=$arr[nonce_str]&package=".'prepay_id='."$arr[prepay_id]&signType=MD5&timeStamp=$timeStamp";
        $stringSignTemp="$stringA&key=".\WxPayConf_pub::KEY;

        $sign=MD5($stringSignTemp);
        $arr['sign']=strtoupper($sign);
        return json($arr);

    }
    public function paySuccess()
    {
        $order_id = input("order_id", '', 'htmlspecialchars_decode');
        $row = db::name('facescore_reward')->where("id",$order_id)->find();
        if($row['status'] == 1) {
            return json(['msg' => 'success']);
        }

    }
    public function notify(){

        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = file_get_contents("php://input");
        $notify->saveData($xml);

        //  $returnXml = $notify->returnXml();
        $log_name="D://notify_url.log";//log文件路径

        $notify->setReturnParameter("return_code","SUCCESS");//设置返回码

        $order_id = substr($notify->data["out_trade_no"],9);
        $total_fee = $notify->data["total_fee"];
        $openid = $notify->data["openid"];

        $order = db::name('facescore_reward')->where("id",$order_id)->find();
        //被打赏人
        $bei_user =  db::name('facescore_content')->where("id",$order['content_id'])->find();
        if($notify->data["return_code"] == "SUCCESS"){
            if($total_fee == ($order['money'] * 100)) {
                //事务
                try{
                    Db::startTrans();
                    //处理设置订单支付成功
                    db::name('facescore_reward')->where('id',$order_id)->update(['status'=>'1']);

                    //打赏人加一条流水记录
                    $flow_data = [
                        'time' => date('Y-m-d H:i:s',time()),
                        'name' => config('module_facescore.dashangzhichu'),
                        'money' => 0 - (double)$order['money'],
                        'uid' => $order['uid'], //打赏人的uid
                        'type' => 'rmb'
                    ];

                    db::name('facescore_flow')->insert(  $flow_data);

                    //被打赏人实际到账金额 = 订单金额 * 后台设置的费率
                    $money = $order['money'] * config('module_facescore.rmb_rate');
                    //被打赏人加钱
                    db::name('admin_member')->where('id',$bei_user['uid'])->update(['money'=>Db::raw('money+'.$money)]);

                    //平台收入加一条流水记录
                    $flow_data = [
                        'time' => date('Y-m-d H:i:s',time()),
                        'name' => '用户打赏平台收入',
                        'money' => (double)$order['money'] - (double)$money,
                        'uid' => 'facescoreOfficial', //打赏人的uid
                        'type' => 'rmb'
                    ];
                    db::name('facescore_flow')->insert(  $flow_data);

                    //被赏人加一条流水记录
                    $flow_data = [
                        'time' => date('Y-m-d H:i:s',time()),
                        'name' => config('module_facescore.dashangshouru'),
                        'money' => $money,
                        'uid' => $bei_user['uid'], //打赏人的uid
                        'type' => 'rmb'
                    ];
                    db::name('facescore_flow')->insert($flow_data);

                     //提交事务
                    Db::commit();
                } catch (\Exception $e) {
                     //回滚事务

                    Db::rollback();
                }
            }
            $this->log_result($log_name,"【succsss】:\n".$xml."\n");
            $this->return_xml_success('OK');
            return true;
        }
    }

    function  log_result($file,$word)
    {
        $fp = fopen($file,"a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,"执行日期：".strftime("%Y-%m-%d-%H：%M：%S",time())."\n".$word."\n\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

    private function set_xml($args)
    {
        $xml = "<xml>";
        foreach ($args as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    private function return_xml_success($msg){
        $arr = array(
            'return_code'   =>  'SUCCESS',
            'return_msg'    =>  $msg
        );
        echo $this->set_xml($arr);
        exit();
    }
}
